package com.smart.community.region.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.commons.utils.SecurityUtils;
import com.smart.community.feign.property.service.DataScopeFeign;
import com.smart.community.region.dto.ShopOwnerRelationDTO;
import com.smart.community.region.entity.ShopOwnerRelation;
import com.smart.community.region.mapper.ShopOwnerRelationMapper;
import com.smart.community.region.service.IShopOwnerRelationService;
import com.smart.community.region.vo.ShopOwnerRelationVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import io.seata.spring.annotation.GlobalTransactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 店铺业主关联服务实现类
 * 
 * @author Wu.Liang
 * @version 1.0.0
 * @since 2025-01-30
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ShopOwnerRelationServiceImpl extends ServiceImpl<ShopOwnerRelationMapper, ShopOwnerRelation> 
        implements IShopOwnerRelationService {

    private final ShopOwnerRelationMapper shopOwnerRelationMapper;
    
    @Autowired
    private DataScopeFeign dataScopeFeign;

    @Override
    @Cacheable(value = "shop:owner:relations", key = "#shopId")
    public List<ShopOwnerRelationVO> getOwnersByShopId(Long shopId) {
        log.info("根据店铺ID获取业主列表，店铺ID: {}", shopId);
        return shopOwnerRelationMapper.selectOwnersByShopId(shopId);
    }

    @Override
    @Cacheable(value = "shop:owner:relations", key = "'owner:' + #ownerId + '_' + T(com.smart.community.commons.utils.SecurityUtils).getCurrentUserId()")
    public List<ShopOwnerRelationVO> getShopsByOwnerId(Long ownerId) {
        log.info("根据业主ID获取店铺列表，业主ID: {}", ownerId);
        
        try {
            // 获取当前用户ID
            Long currentUserId = SecurityUtils.getCurrentUserId();
            if (currentUserId == null) {
                log.warn("用户未登录，无法获取店铺列表");
                return Collections.emptyList();
            }
            
            // 判断用户是否为超级管理员
            Boolean isSuperAdmin = dataScopeFeign.isUserSuperAdmin(currentUserId);
            if (isSuperAdmin == null) {
                log.warn("无法获取用户权限信息，用户ID: {}", currentUserId);
                return Collections.emptyList();
            }
            
            if (isSuperAdmin) {
                // 超级管理员可以查看所有店铺数据
                log.info("用户{}是超级管理员，可以查看所有店铺数据", currentUserId);
                return shopOwnerRelationMapper.selectShopsByOwnerId(ownerId);
            } else {
                // 普通用户：先获取用户关联的社区IDs，然后根据社区IDs筛选店铺数据
                log.info("用户{}是普通用户，需要根据社区权限过滤店铺数据", currentUserId);
                
                // 获取用户关联的社区IDs
                List<Long> userCommunityIds = dataScopeFeign.getUserCommunityIds(currentUserId);
                if (userCommunityIds == null || userCommunityIds.isEmpty()) {
                    log.warn("用户{}未关联任何社区，无法查看店铺数据", currentUserId);
                    return Collections.emptyList();
                }
                
                log.info("用户{}关联的社区IDs: {}", currentUserId, userCommunityIds);
                
                // 根据社区IDs筛选店铺数据
                return shopOwnerRelationMapper.selectShopsByOwnerIdWithCommunityIds(ownerId, userCommunityIds);
            }
            
        } catch (Exception e) {
            log.error("根据业主ID获取店铺列表失败，业主ID: {}", ownerId, e);
            return Collections.emptyList();
        }
    }



    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = "shop:owner:relations", allEntries = true)
    public boolean batchSetShopOwnerRelations(List<ShopOwnerRelationDTO> relationList) {
        log.info("批量设置店铺业主关联，关联数量: {}", relationList.size());
        
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            if (currentUserId == null) {
                log.warn("用户未登录，无法批量设置关联关系");
                return false;
            }
            
            // 批量创建新的关联关系
            for (ShopOwnerRelationDTO relationDTO : relationList) {
                ShopOwnerRelation relation = new ShopOwnerRelation();
                relation.setShopId(relationDTO.getShopId());
                relation.setOwnerId(relationDTO.getOwnerId());
                relation.setRelationType(relationDTO.getRelationType());
                relation.setOwnershipRatio(relationDTO.getOwnershipRatio());
                relation.setLeaseStartDate(relationDTO.getLeaseStartDate());
                relation.setLeaseEndDate(relationDTO.getLeaseEndDate());
                relation.setRentPrice(relationDTO.getRentPrice());
                relation.setDepositAmount(relationDTO.getDepositAmount());
                relation.setContractNumber(relationDTO.getContractNumber());
                relation.setContractFile(relationDTO.getContractFile());
                relation.setIsPrimary(relationDTO.getIsPrimary());
                relation.setStatus(relationDTO.getStatus());
                relation.setRemark(relationDTO.getRemark());
                relation.setCreateTime(LocalDateTime.now());
                relation.setUpdateTime(LocalDateTime.now());
                relation.setCreateBy(currentUserId);
                relation.setUpdateBy(currentUserId);
                
                save(relation);
            }
            
            log.info("成功批量设置关联关系，共{}条", relationList.size());
            return true;
            
        } catch (Exception e) {
            log.error("批量设置店铺业主关联关系失败", e);
            return false;
        }
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = "shop:owner:relations", allEntries = true)
    public Long createShopOwnerRelation(ShopOwnerRelationDTO relationDTO) {
        log.info("创建店铺业主关联关系，店铺ID: {}, 业主ID: {}", relationDTO.getShopId(), relationDTO.getOwnerId());
        
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            if (currentUserId == null) {
                log.warn("用户未登录，无法创建关联关系");
                throw new RuntimeException("用户未登录");
            }
            
            // 创建关联关系
            ShopOwnerRelation relation = new ShopOwnerRelation();
            relation.setShopId(relationDTO.getShopId());
            relation.setOwnerId(relationDTO.getOwnerId());
            relation.setRelationType(relationDTO.getRelationType());
            relation.setOwnershipRatio(relationDTO.getOwnershipRatio());
            relation.setLeaseStartDate(relationDTO.getLeaseStartDate());
            relation.setLeaseEndDate(relationDTO.getLeaseEndDate());
            relation.setRentPrice(relationDTO.getRentPrice());
            relation.setDepositAmount(relationDTO.getDepositAmount());
            relation.setContractNumber(relationDTO.getContractNumber());
            relation.setContractFile(relationDTO.getContractFile());
            relation.setIsPrimary(relationDTO.getIsPrimary());
            relation.setStatus(relationDTO.getStatus());
            relation.setRemark(relationDTO.getRemark());
            relation.setCreateTime(LocalDateTime.now());
            relation.setUpdateTime(LocalDateTime.now());
            relation.setCreateBy(currentUserId);
            relation.setUpdateBy(currentUserId);
            
            boolean result = save(relation);
            if (result) {
                log.info("成功创建店铺业主关联关系，关联ID: {}", relation.getId());
                return relation.getId();
            } else {
                log.error("创建店铺业主关联关系失败");
                throw new RuntimeException("创建关联关系失败");
            }
            
        } catch (Exception e) {
            log.error("创建店铺业主关联关系失败", e);
            throw new RuntimeException("创建关联关系失败：" + e.getMessage());
        }
    }
    
    @Override
    @Cacheable(value = "shop:owner:relation:page", key = "#page.current + '_' + #page.size + '_' + #shopId + '_' + #ownerId + '_' + #relationType + '_' + #status")
    public IPage<ShopOwnerRelationVO> getShopOwnerRelationPage(Page<ShopOwnerRelation> page, Long shopId, Long ownerId, Integer relationType, Integer status) {
        log.info("分页查询店铺业主关联关系列表，当前页：{}，每页大小：{}，店铺ID：{}，业主ID：{}，关系类型：{}，状态：{}", 
                page.getCurrent(), page.getSize(), shopId, ownerId, relationType, status);
        
        try {
            return shopOwnerRelationMapper.selectShopOwnerRelationPage(page, shopId, ownerId, relationType, status);
        } catch (Exception e) {
            log.error("分页查询店铺业主关联关系列表失败", e);
            return new Page<>(page.getCurrent(), page.getSize(), 0);
        }
    }
    
    @Override
    @Cacheable(value = "shop:owner:relation:detail", key = "#id")
    public ShopOwnerRelationVO getShopOwnerRelationById(Long id) {
        log.info("查询店铺业主关联关系详情，关联ID: {}", id);
        
        try {
            ShopOwnerRelation relation = getById(id);
            if (relation == null) {
                log.warn("店铺业主关联关系不存在，关联ID: {}", id);
                return null;
            }
            
            return shopOwnerRelationMapper.selectOwnerRelationVOById(id);
            
        } catch (Exception e) {
            log.error("查询店铺业主关联关系详情失败，关联ID: {}", id, e);
            return null;
        }
    }
    
    @Override
    @Cacheable(value = "shop:owner:primary", key = "#shopId")
    public ShopOwnerRelationVO getPrimaryContactByShopId(Long shopId) {
        log.info("获取店铺主要联系人，店铺ID: {}", shopId);
        
        LambdaQueryWrapper<ShopOwnerRelation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShopOwnerRelation::getShopId, shopId)
                .eq(ShopOwnerRelation::getIsPrimary, 1)
                .orderByDesc(ShopOwnerRelation::getCreateTime)
                .last("LIMIT 1");
        
        ShopOwnerRelation relation = getOne(queryWrapper);
        if (relation != null) {
            return shopOwnerRelationMapper.selectOwnerRelationVOById(relation.getId());
        }
        
        return null;
    }
    
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = "shop:owner:relations", allEntries = true)
    public boolean updateShopOwnerRelation(Long id, ShopOwnerRelationDTO relationDTO) {
        log.info("更新店铺业主关联关系，关联ID: {}", id);
        
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            if (currentUserId == null) {
                log.warn("用户未登录，无法更新关联关系");
                return false;
            }
            
            // 检查关联关系是否存在
            ShopOwnerRelation existingRelation = getById(id);
            if (existingRelation == null) {
                log.warn("店铺业主关联关系不存在，关联ID: {}", id);
                return false;
            }
            
            // 更新关联关系
            ShopOwnerRelation relation = new ShopOwnerRelation();
            relation.setId(id);
            relation.setShopId(relationDTO.getShopId());
            relation.setOwnerId(relationDTO.getOwnerId());
            relation.setRelationType(relationDTO.getRelationType());
            relation.setOwnershipRatio(relationDTO.getOwnershipRatio());
            relation.setLeaseStartDate(relationDTO.getLeaseStartDate());
            relation.setLeaseEndDate(relationDTO.getLeaseEndDate());
            relation.setRentPrice(relationDTO.getRentPrice());
            relation.setDepositAmount(relationDTO.getDepositAmount());
            relation.setContractNumber(relationDTO.getContractNumber());
            relation.setContractFile(relationDTO.getContractFile());
            relation.setIsPrimary(relationDTO.getIsPrimary());
            relation.setStatus(relationDTO.getStatus());
            relation.setRemark(relationDTO.getRemark());
            relation.setUpdateTime(LocalDateTime.now());
            relation.setUpdateBy(currentUserId);
            
            boolean result = updateById(relation);
            if (result) {
                log.info("成功更新店铺业主关联关系，关联ID: {}", id);
            } else {
                log.warn("更新店铺业主关联关系失败，关联ID: {}", id);
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("更新店铺业主关联关系失败，关联ID: {}", id, e);
            return false;
        }
    }
    
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    @CacheEvict(value = "shop:owner:relations", allEntries = true)
    public boolean deleteShopOwnerRelation(Long id) {
        log.info("删除店铺业主关联关系，关联ID: {}", id);
        
        try {
            Long currentUserId = SecurityUtils.getCurrentUserId();
            if (currentUserId == null) {
                log.warn("用户未登录，无法删除关联关系");
                return false;
            }
            
            // 检查关联关系是否存在
            ShopOwnerRelation existingRelation = getById(id);
            if (existingRelation == null) {
                log.warn("店铺业主关联关系不存在，关联ID: {}", id);
                return false;
            }
            
            // 物理删除关联关系
            boolean result = removeById(id);
            if (result) {
                log.info("成功删除店铺业主关联关系，关联ID: {}, 店铺ID: {}, 业主ID: {}", 
                        id, existingRelation.getShopId(), existingRelation.getOwnerId());
            } else {
                log.warn("删除店铺业主关联关系失败，关联ID: {}", id);
            }
            
            return result;
            
        } catch (Exception e) {
            log.error("删除店铺业主关联关系失败，关联ID: {}", id, e);
            return false;
        }
    }
}